/**
 * Copyright(C) com.allinpay - 老纳慢走
 * 
 * @akonziz 陆某人
 *
 * @since 2013年9月25日
 * @description: <描述>
 * 
 */

var thour = new Array();
var addresses = new Array();
var dinnerDate = "";

$(document).ready(function() {
	$('#hours').change(function(){ 
		var v=$(this).children('option:selected').val();//这就是selected的值 
		buildTimeMinsOption(v,"mins");
	}) ;
	$('#mins').change(function(){
		setTimeout("request_avaliable_seatcategory('" + getDinnerTimeForSubmit() +"', 'seats')", 10);
	}) ;
	$('#seats').change(function(){
		var v=$(this).children('option:selected').val();//这就是selected的值 
		$("#seatCatId").val(v);
	}) ;
	
/*	$("#contactPhone").blur(function(){
		if (!isValidPhoneNumber(this.value)){
			setInfoMsg("手机号码格式不对", true);
		}
	});*/

	$("#address_reserved").click(function() {
		var nextGo = $(this).next();
		//$("#address").css({});
		//$("#address").not(nextGo).slideUp("slow");
		nextGo.animate({
			height : 'toggle',
			opacity : 'toggle',
			duration : "slow"
		}, function(){
			if ($(this).css('display') == 'none'){
				$("#address_reserved").removeClass('xl-infor-f-up');
				$("#address_reserved").addClass('xl-infor-f');
			}else{
				$("#address_reserved").removeClass('xl-infor-f');
				$("#address_reserved").addClass('xl-infor-f-up');
			}
		});
		return false;
	});
	
	$("#reserveform").submit(function(e){
		var target = "apis/restaurant/reserve";
		var ajax_data = {
			"rid" : r_id,
			"dinnerTime" : getDinnerTimeForSubmit(),
			"seatCatId" : $("#seatCatId").val(),
			"address_id" : $("#address_id").val(),
			"contactPerson" : $("#contactPerson").val(),
			"contactPhone" : $("#contactPhone").val(), 
			"access_token" : access_token
		};
		
		$("#nextButton").toggleClass("b-btn-red-active");
		setTimeout(function() {
			$("#nextButton").toggleClass("b-btn-red-active");
		},100);

		if (!checkSubmitInfo(ajax_data)) {
			e.preventDefault();
		}else{
			if (ajax_data.address_id == "" || ajax_data.address_id == null) {
				ajax_data.address_id = -1;
			}
			ajax_post_json(target, ajax_data, function() {
				setInfoMsg("正在提交信息，请稍候...", false);
				$("#nextButton").attr("disabled","true");
			}, function(data) {
				if (data.result == true) {
					setTimeout("goMenu('" + $("#next_t").val() + "')", 10);
				} else if (data.result == false) {
					setInfoMsg(data.content, true);
					$("#nextButton").removeAttr("disabled");
				}
			}, function(xhr, textStatus, errorThrown) {
				ef_alert("reserve submit: " + xhr.status + ",  " + xhr.statusText);
				setInfoMsg("系统繁忙，请稍后重试", true);
/*				if (xhr.status == 504) {  //Gateway Timeout 
					setInfoMsg("系统繁忙，请稍后重试", true);
				}else{
					setInfoMsg(xhr.statusText, true);
				}*/
				$("#nextButton").removeAttr("disabled");
			}, function(event,xhr,options) {
			});
			return false;
		}
	});
	
	buildWeekTable(period, "week_table_body");

	request_customer_address("addresses_reserved");

	var todayStr = date2String(new Date());
	request_dinner_time(todayStr);                //"2013-10-30 09:41:12"
});


function date2String(date){     // 2014-01-03 09:50:00  (js 0 ~ 11  一月~ 十二月) 
	var todayArr = date.toArray();
	
	var todayStr = todayArr[0];                   //year  4
	todayStr = todayStr + "-";
	todayStr += format2digit(todayArr[1]+1); // month 2     
	todayStr = todayStr + "-";
	todayStr += format2digit(todayArr[2]);    // day 2
	
	todayStr = todayStr + " ";
	todayStr += format2digit(todayArr[3]);    // hour 2
	todayStr = todayStr + ":";
	todayStr += format2digit(todayArr[4]);    // min 2
	todayStr = todayStr + ":";
	todayStr += format2digit(todayArr[5]);    // sec 2
	
	//ef_alert("reserve date2string: " + todayStr);
	return todayStr;
}

function checkSubmitInfo(data) {
	
	if (!isValidDate(data.dinnerTime)){
		setInfoMsg("就餐时间未选择，或今天已过预定时段", true);
		return false;
	}
	if (data.seatCatId == -1) {
		setInfoMsg("请选择餐位", true);
		return false;
	}
	if (data.contactPerson.trim() == "") {
		setInfoMsg("客户姓名不能为空", true);
		return false;
	}
	if (data.contactPhone.trim() == "") {
		setInfoMsg("手机号码不能为空", true);
		return false;
	}
	if (!isValidPhoneNumber(data.contactPhone)){
		setInfoMsg("手机号码格式不对", true);
		return false;
	}
	data.contactPerson = data.contactPerson.trim();
	return true;
}

function goMenu(url){
	window.location.href = url;
	return false;
}

function getDinnerTimeForSubmit(){
	var hour = $("#hours").children('option:selected').val();
	var min = $("#mins").children('option:selected').val();
	
	if (parseInt(hour) == -1 || parseInt(min) == -1) {
		return "";
	}
	
	// 2013-10-29 21:30:00
/*	var todayArr = (new Date()).toArray();
	var timeStr = todayArr[0];                     //year  4
	timeStr = timeStr + "-";
	timeStr += format2digit(todayArr[1]+1);   // month 2
	timeStr = timeStr + "-";
	timeStr += format2digit(todayArr[2]);      // day 2
*/	
	timeStr = dinnerDate;     // 获取用户选择的日期  2014-01-02
	
	timeStr = timeStr + " ";
	timeStr += format2digit(parseInt(hour));   // hour 2
	timeStr = timeStr + ":";
	timeStr += format2digit(parseInt(min));    // min 2
	timeStr = timeStr + ":";
	timeStr += format2digit(0);                    // sec 2

	//ef_alert("getDinnerTimeForSubmit: " + timeStr);
	return timeStr;
}

function beforeSend(){
};
function m_error(xhr, textStatus, errorThrown){
}

function request_dinner_time(t_date) {
	ajax_post_json("apis/restaurant/dinnerTime", {
		"rid" : r_id,
		"dinnerDate" : t_date,
		"access_token":access_token
	}, beforeSend, function(data) {
		thour.length = 0;
		if (data.result == true){
			initDinnerTime(data.content);
		}else{
			setTimeout(buildTimeHoursOption('hours'),10);
		}
	}, m_error);
}

function newDinnerTime(hour, mins){
	var dt = new Object();
	dt.hour = hour;
	dt.mins = mins;
	return dt;
}

function initDinnerTime(data){
	$.each(data, function(index, item) {
		var minArr = new Array();
		$.each(item.mins, function(index1, item1) {
			minArr[index1] = item1;
		});
		thour[index] = newDinnerTime(item.hour, minArr);
	});
	setTimeout(buildTimeHoursOption('hours'),10);
}

function buildTimeHoursOption(elementId){
	var optionHtml = "";
	var fisrt = -1;
	$.each(thour, function(index, item) {
		if (index == 0) fisrt = item.hour;
		optionHtml += "<option value=\"" + item.hour + "\">" + item.hour + "</option>";
	});
	
	if (optionHtml == "") {
		optionHtml = "<option value=\"" + -1 + "\">" + "小时" + "</option>";
	}
	$("#" + elementId).empty();
	$("#" + elementId).append(optionHtml);
	buildTimeMinsOption(fisrt, "mins");
}

function buildTimeMinsOption(hour,elementId){
	var mins = [];
	$.each(thour, function(index, item) {
		if (item.hour == hour) mins = item.mins;
	});

	var optionHtml = "";
	if (hour == -1) {
		optionHtml = "<option value=\"" + -1 + "\">" + "分钟" + "</option>";
	}else {
		$.each(mins, function(index, item) {
			if (item < 10){
				optionHtml += "<option value=\"0" + item + "\">0" + item + "</option>";
			}else{

				optionHtml += "<option value=\"" + item + "\">" + item + "</option>";
			}
		});
	}
	$("#" + elementId).empty();
	$("#" + elementId).append(optionHtml);

	setTimeout("request_avaliable_seatcategory('" + getDinnerTimeForSubmit() +"', 'seats')", 10);
}

function choose_reserved_address(id, contact, phone){
	$("#address_id").val(id);
	$("#contactPerson").val(contact);
	$("#contactPhone").val(phone);
}

function choose_address(id, contact, phone, address){
	choose_reserved_address(id, contact, phone, address);
	
	var input = $("#address_list").find("input:radio");
	 input.each(function(){
		 if (this.id == id){
			 this.checked = true;
		 }
	 });
}

function newAddress(id, contact, phone, address){
	var addr = new Object();
	addr.id = id;
	addr.contact = contact;
	addr.phone = phone;
	addr.address=address;
	return addr;
}

function request_customer_address(elementId){
	ajax_post_json("apis/user/address", {
		"user_id" : u_id,
		"option" : "RETRIEVE_ALL", 
		"access_token":access_token
	}, beforeSend, function(data) {
		var pHtml = "";
		var count = 0;
		pHtml += "<div id=\"address_list\" style=\"padding-left: 0px; border-spacing:5px;\">";
		$.each(data.content, function(index, item) {
			pHtml += "<div class=\"center-f\">";
			pHtml += "<input type=\"radio\" id=\""+item.id+"\" name=\"addr_radio\" value=\"" + item.id + "\"> ";
			pHtml += "<a href=\"javascript:choose_address('"+item.id+"','"+item.contactPerson+"','"+item.contactTel+"','"+(item.addressArea+" "+ item.contactAddress)+"')\"";
			pHtml += "<span style=\"color:#333;\">" +item.contactPerson+"</span>";
			pHtml += "<span style=\"color:#333; padding-left:18px;\">" +item.contactTel+"</span><br/>";
			pHtml += "<span style=\"color:#333; padding-left:18px;\">" +item.addressArea +" " + item.contactAddress+"</span>";
			pHtml += "</a></div>";
			
			addresses[index] = newAddress(item.id, item.contactPerson, item.contactTel, item.addressArea+" "+ item.contactAddress);
			count++;
		});
		pHtml += "</div>";
		
		$("#" + elementId).empty();
		$("#" + elementId).append(pHtml);
		
		 var input = $("#address_list").find("input:radio");
		 input.each(function(){
			 if (this.id == $("#address_id").val()){
				 this.checked = true;
			 }
		 });
			
		$("input[type=radio][name=addr_radio]").click(function() {
			var cur_addr_id = this.id;
			$.each(addresses, function(index, item){
				if (item.id == cur_addr_id){
					choose_reserved_address(item.id, item.contact, item.phone);
					return false;
				}
			});
		});
	}, m_error);
}

function request_avaliable_seatcategory(date, elementId){
	if (date=="") {
		optionHtml = "<option value=\"" + -1 + "\">" + "无预订位" + "</option>";
		$("#" + elementId).empty();
		$("#" + elementId).append(optionHtml);
		return;
	}
	
	ajax_post_json("apis/restaurant/seatCategoryStatus", {
		"rid" : r_id,
		"dinnerTime":date, 
		"access_token":access_token
	}, beforeSend, function(data) {
		var optionHtml = "";
		if (data.result == true){
			$.each(data.content, function(index, item) {
				optionHtml += "<option value=\"" + item.category.id + "\">" + item.category.name + "(" +item.category.minNumOfPeople + "~" + item.category.maxNumOfPeople + "人)" + ((item.acceptreservation == false)?"  - 满":"")+ "</option>";                                                                                          
			});
			if (optionHtml != "") {
				optionHtml = "<option value=\"" + -1 + "\">" + "餐位选择" + "</option>" + optionHtml;
			}
		}
		if (optionHtml == ""){
			optionHtml = "<option value=\"" + -1 + "\">" + "无预订位" + "</option>";
		}
		$("#" + elementId).empty();
		$("#" + elementId).append(optionHtml);
	}, m_error);
}

function selectedDinnerDate(date){
	dinnerDate = date;       // format:  2014-01-02  with no time
	
	var todayArr = (new Date()).toArray();
	var todayStr = todayArr[0];                     //year  4
	todayStr = todayStr + "-";
	todayStr += format2digit(todayArr[1]+1);   // month 2
	todayStr = todayStr + "-";
	todayStr += format2digit(todayArr[2]);      // day 2

	//ef_alert("reserve selectedDinnerDate:  " + date + ",  " + todayStr + "   " + (date == todayStr));
	if (date == todayStr) {
		date = date2String(new Date());
	}else{
		date += " 02:00:00";
	}
	
	request_dinner_time(date);  //"2013-10-30 09:41:12"
	
	// 修改选中的样式，还原未选中的样式
	$("table tbody tr td").each(function(){
		$(this).removeClass('click');
	});
	
	var arys= date.split('-');
	var arys2 = arys[2].split(' ');
	$("#"+parseInt(arys2[0])).toggleClass("click");
	
	// 设置当前月份
	$("#cur_chinese_month").html(getChineseMonth(parseInt(arys[1])-1));
}

function getChineseMonth(m){
    var Month = ['一月','二月','三月','四月','五月','六月','七月', '八月', '九月', '十月', '十一月', '十二月'];
	return Month[m];
}

function buildWeekTable(period, elementId){
	
	var tableHtml = "";
	
	var today = new Date() ;// new Date('2013','10','1');
//	today.getYear();        //获取当前年份(2位)
//	today.getFullYear();    //获取完整的年份(4位,1970-????)
//	today.getMonth();       //获取当前月份(0-11,0代表1月)
//	today.getDate();        //获取当前日(1-31)

	tableHtml += "<tbody>";
	var trHtml = "<tr>";
	var perCount = today.getDay();
	var todayDate = today.getDate();
	var curYear = today.getFullYear();
	var curMonth = today.getMonth();

	dinnerDate = curYear + "-" + format2digit(curMonth + 1) + "-" + format2digit(todayDate);
	$("#cur_chinese_month").html(getChineseMonth(curMonth));
	//ef_alert("buildWeekTable today: " + dinnerDate);
	
	var countWeek = (perCount + period) / 7;
	var cycle = 7 * Math.round(countWeek + 0.4);
	var bStart = false;
	var specialDate = "";
	var maxDayofMonth = today.MaxDayOfDate();
	if (perCount == 0){ //刚好是星期天
		for (var i=0;i<cycle;i++) {
			
			var showtime = todayDate;
//			specialDate = curYear + "-" + ((curMonth+1 > 9) ?(curMonth+1):("0"+(curMonth+1))) + "-";
//			specialDate += (todayDate > 9)?todayDate:("0"+todayDate) ;
			specialDate = curYear + "-" + format2digit(curMonth + 1) + "-" + format2digit(todayDate);
			
			if ((i > 0 )&& (i % 7 == 0)) trHtml += "</tr><tr>";
			
			if (showtime == today.getDate()){
				trHtml += "<td id="+showtime+"";
				trHtml += (i % 7 == 0)?" class=\"c-td-th click\" ":" class=\"c-td click\"";
				trHtml +=" ><a href=\"javascript:selectedDinnerDate('" + specialDate +"')\">" + showtime + "</a></td>";
				bStart = true;
			}else if (bStart && (period--)> 1) {  //排除当前
				trHtml += "<td id="+showtime+"";
				trHtml += (i % 7 == 0)?" class=\"c-td-th\" ":" class=\"c-td\"";
				trHtml +=" ><a href=\"javascript:selectedDinnerDate('" + specialDate +"')\">" + showtime + "</a></td>";
			}else{
				trHtml += "<td id="+showtime+"";
				trHtml += (i % 7 == 0)?" class=\"c-td-th no-click\" ":" class=\"c-td no-click\"";
				trHtml += ">" + showtime + "</a></td>";
			}
			
			todayDate ++;
			if (todayDate > maxDayofMonth) {
				todayDate = 1;
				curMonth = (curMonth + 1) % 12;  // 月份(0-11,0代表1月)
				if (curMonth == 0) curYear = curYear+1;
			}
		}
		trHtml += "</tr>";
	}else{
		for (var i=0;i<cycle;i++)
		{
			var showtime = (todayDate-perCount + i);
			if (showtime <=0){  // 说明是月初，获取上一个月的最大天数，倒数
				var lastYear = curYear;
				var lastMonth = (curMonth - 1 + 12) %12;
				if (lastMonth == 11)  lastYear = lastYear - 1;
				showtime = showtime + (new Date(lastYear, lastMonth, '1').MaxDayOfDate());
				
//				specialDate = lastYear + "-" + ((lastMonth+1 > 9) ?(lastMonth+1):("0"+(lastMonth+1))) + "-";
//				specialDate += (showtime > 9)?(showtime):("0"+showtime)  ;

				specialDate = lastYear + "-" + format2digit(lastMonth + 1) + "-" + format2digit(showtime);
				
			}else{
//				specialDate = curYear + "-" + ((curMonth+1 > 9) ?(curMonth+1):("0"+(curMonth+1))) + "-";
//				specialDate += (showtime > 9)?(showtime):("0"+showtime);
				
				specialDate = curYear + "-" + format2digit(curMonth + 1) + "-" + format2digit(showtime);
			}
			
			if ((i > 0 )&& (i % 7 == 0)) trHtml += "</tr><tr>";
			
			if (showtime == today.getDate()){
				trHtml += "<td id="+showtime+"";
				trHtml += (i % 7 == 0)?" class=\"c-td-th today-time click\" ":" class=\"c-td today-time click\" ";
				trHtml +=" ><a href=\"javascript:selectedDinnerDate('" + specialDate +"')\">" + showtime + "</a></td>";
				bStart = true;
			}else if (bStart && (period--)> 1) {  //排除当前
				trHtml += "<td  id="+showtime+"";
				trHtml += (i % 7 == 0)?" class=\"c-td-th\" ":" class=\"c-td\" ";
				trHtml +=" ><a href=\"javascript:selectedDinnerDate('" + specialDate +"')\">" + showtime + "</a></td>";
			}else{
				trHtml += "<td  id="+showtime+"";
				trHtml += (i % 7 == 0)?" class=\"c-td-th no-click\" ":" class=\"c-td no-click\" ";
				trHtml += ">" + showtime + "</a></td>";
			}
			
			if ((todayDate-perCount + i) >= maxDayofMonth) {
				todayDate = perCount - i ;
				curMonth = (curMonth + 1) % 12;  // 月份(0-11,0代表1月)
				if (curMonth == 0) curYear = curYear+1;
			}
		}
		trHtml += "</tr>";
	}
	tableHtml = tableHtml + trHtml;
	tableHtml += "</tbody>";
	
	$("#" + elementId).empty();
	$("#" + elementId).append(tableHtml);
}

function prompt_info_animate() {
	$("#prompt_info_c").animate({
		height : 'toggle',
		opacity : 'toggle',
		duration : "slow"
	}, function(){
		if ($("#prompt_info").hasClass("prompt_info_down")) {
			$("#prompt_info").removeClass("prompt_info_down");
			$("#prompt_info").addClass("prompt_info_up");
		}else{
			$("#prompt_info").removeClass("prompt_info_up");
			$("#prompt_info").addClass("prompt_info_down");
		}
	});
}

function setInfoMsg(msg, disappear){
	
	if (isValide(msg) && msg.length > 0) {
		$("#info_msg").html(msg);
		$("#info_msg_div").css({"display":"block", "height":"0px", "lineHeight":"20px"});
		$("#info_msg_div").animate({
			height : '20px',
			duration : "slow"
		}, function(){});
	}else {
		$("#info_msg_div").animate({
			height : '0px',
			duration : 'slow'
		}, function(){
			$("#info_msg_div").css({"display":"none", "height":"0px"});
			$("#info_msg").html(msg);
		});
	}
	
	if (disappear){
		setTimeout("setInfoMsg('', false)", 5000);
	}
}